package org.dfl.core.model.transitions;

import org.dfl.core.model.XMLLoaderException;
import org.dfl.messages.Messages;
import org.jdom.Element;
import org.jdom.Namespace;

/**
 * factory that creates transitions
 * @author Piotr Wlodarczyk
 *
 */
public class TransitionFactory {
	/**
	 * load transition from an XML Element
	 * @param tElem - XML element
	 * @return transition
	 * @throws XMLLoaderException
	 */
	public static Transition loadTransition(Element tElem) throws XMLLoaderException{
		return loadTransition(tElem, tElem.getNamespace());		
	}
	
	/**
	 * load transition from an XML Element with a given namespace
	 * @param tElem - XML Element
	 * @param namespace
	 * @return transition
	 * @throws XMLLoaderException
	 */
	public static Transition loadTransition(Element tElem, Namespace namespace) throws XMLLoaderException{
		Transition t = getEmptyTransition(tElem, namespace);
		t.load(tElem);
		return t;
	}

	public static Transition getEmptyTransition(Element tElem) throws XMLLoaderException{
		return getEmptyTransition(tElem,tElem.getNamespace());
	}
	
	@SuppressWarnings("unchecked")
	public static Transition getEmptyTransition(Element tElem, Namespace namespace) throws XMLLoaderException{
		String type = tElem.getAttributeValue("type",namespace); //$NON-NLS-1$
		
		try{
			if(!type.contains(".")){ //$NON-NLS-1$
				final String packageName = TransitionFactory.class.getPackage().getName();
				type = packageName+"."+type; //$NON-NLS-1$
			}
			Class classDefinition = Class.forName(type);
			Transition t = (Transition) classDefinition.newInstance();
			return t;
		}catch(Exception e){
			String id = tElem.getAttributeValue("id",namespace); //$NON-NLS-1$
			throw new XMLLoaderException(Messages.TransitionFactory_errorTransitionType1+id+Messages.TransitionFactory_errorTransitionType2+type+Messages.TransitionFactory_errorTransitionType3,e);
		}
	}
}